<template>
  <div id="detail">
    <s-header :name="'商品详情'" :back="'/home'"></s-header>
    <nav-bar />

    <div class="dc">
      <div class="content w">
        <div class="title fl">商品详情</div>
        <div class="clear"></div>
      </div>
    </div>

    <div class="intro mt20 w clearfix">
      <div class="left fl">
        <div class="swiper-container fl">
          <img :src="seckillGoods.goodsCoverImg" id="goodsImg" />
        </div>
      </div>
      <div class="right fr">
        <h2 class="text-danger">
          <span class="glyphicon glyphicon-time"></span>
          <span id="seckillBox">{{ countdown }}</span>
        </h2>
        <div class="h3" id="goodsName">{{ seckillGoods.goodsName }}</div>
        <div class="sub_title" id="goodsIntro">{{ seckillGoods.goodsIntro }}</div>
        <div class="item_price">
          秒杀价：<span id="seckillPrice">{{ seckillGoods.seckillPrice }} 元</span>
          <del id="originalPrice">{{ seckillGoods.sellingPrice }} 元</del>
        </div>

        <div class="order">
          <input type="hidden" id="userId" :value="userId" />
          <button class="btn btn-danger btn-lg" :disabled="!seckillActive" @click="startSeckill">
            {{ seckillActive ? '立即抢购' : '秒杀未开始' }}
          </button>
        </div>
        <div class="tb-extra" id="J_tbExtra">
          <dl>
            <dt>承诺</dt>
            <dd>
              <a
                  class="J_Cont"
                  title="满足7天无理由退换货申请的前提下，包邮商品需要买家承担退货邮费，非包邮商品需要买家承担发货和退货邮费。"
                  href="#"
                  target="_blank"
              >
                <img src="@/assets/7d.jpg" alt="7天无理由" />7天无理由
              </a>
            </dd>
          </dl>
          <dl>
            <dt>支付</dt>
            <dd>
              <a href="##" target="_blank"><img src="@/assets/hua.png" alt="蚂蚁花呗" />蚂蚁花呗</a>
              <a href="##" target="_blank"><img src="@/assets/card.png" alt="信用卡支付" />信用卡支付</a>
              <a href="##" target="_blank"><img src="@/assets/ji.png" alt="集分宝" />集分宝</a>
            </dd>
          </dl>
          <dl>
            <dt>支持</dt>
            <dd>
              折旧变现，买新更省钱。<a href="##">详情</a>
            </dd>
          </dl>
        </div>
      </div>
      <div class="clear"></div>
    </div>
    <div class="goods mt20 w clearfix" v-html="seckillGoods.goodsDetailContent"></div>
  </div>
</template>

<script setup>
import { reactive, onMounted, ref } from 'vue';
import {useRoute, useRouter} from 'vue-router';
import axios from 'axios';
import sHeader from '@/components/SimpleHeader.vue';
import navBar from '@/components/NavBar.vue';
import {getSeckillDetailApi} from "@/service/sec-kill";
const router = useRouter()
const route = useRoute();
const seckillId = route.params.id;

const seckillGoods = reactive({
  goodsCoverImg: '',
  goodsName: '',
  goodsIntro: '',
  seckillPrice: '',
  sellingPrice: '',
  goodsDetailContent: '',
  startDate: 0,
  endDate: 0,
});

const countdown = ref('');
const seckillActive = ref(false);

const updateCountdown = () => {
  const now = new Date().getTime();
  const startTime = seckillGoods.startDate;
  const endTime = seckillGoods.endDate;

  if (now < startTime) {
    const timeLeft = startTime - now;
    countdown.value = formatTimeLeft(timeLeft);
    seckillActive.value = false;
  } else if (now < endTime) {
    const timeLeft = endTime - now;
    countdown.value = formatTimeLeft(timeLeft);
    seckillActive.value = true;
  } else {
    countdown.value = '秒杀已结束';
    seckillActive.value = false;
  }
};

const formatTimeLeft = (time) => {
  const days = Math.floor(time / (1000 * 60 * 60 * 24));
  const hours = Math.floor((time % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  const minutes = Math.floor((time % (1000 * 60 * 60)) / (1000 * 60));
  const seconds = Math.floor((time % (1000 * 60)) / 1000);
  return `${days}天 ${hours}时 ${minutes}分 ${seconds}秒`;
};

const startSeckill = async () => {
    // Check if seckill is active
    if (!seckillActive.value) {
      alert('秒杀尚未开始！');
      return;
    }

    // Check if seckill stock is available
    const data = await axios.post(`/seckill/${seckillId}/checkStock`);
    if (data.resultCode !== 200) {
      alert(data.message || '秒杀商品库存不足！');
      return;
    }

    // Get seckill link
    const { resultCode: exposerResultCode, data: exposerData, message: exposerMessage  } = await axios.post(`/seckill/${seckillId}/exposer`);
    if (exposerResultCode !== 200) {
      alert(exposerMessage || '获取秒杀链接失败！');
      return;
    }

    // Execute seckill
    const { md5:md5Kill } = exposerData;
    const { resultCode: executionResultCode, message: executionMessage,data:{seckillSuccessId,md5:md5Success} } = await axios.post(`/seckillExecution/${seckillId}/${md5Kill}`);
    if (executionResultCode === 200) {
      const {data:orderNO}= await axios.get(`/saveSeckillOrder/${seckillSuccessId}/${md5Success}`);
      await router.push({ path: '/order-detail', query: { id:orderNO } })
      // Optionally, redirect user to seckill success page
    } else {
      alert(executionMessage || '秒杀失败！');
    }

};

const fetchSeckillDetail = async () => {
  try {
    const { data } = await getSeckillDetailApi(seckillId);
    Object.assign(seckillGoods, data);
    updateCountdown();
    setInterval(updateCountdown, 1000);
  } catch (error) {
    console.error('Failed to fetch seckill details:', error);
  }
};

onMounted(() => {
  fetchSeckillDetail();
});
</script>

<style scoped>
#detail {
  padding: 16px;
}

.intro {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.my-swipe {
  width: 100%;
  height: 300px;
}

.goods-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.right {
  width: 100%;
  padding: 16px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.text-danger {
  color: #e74c3c;
  display: flex;
  align-items: center;
  gap: 8px;
}

.goods-name {
  font-size: 24px;
  font-weight: bold;
  margin: 10px 0;
}

.goods-intro {
  font-size: 16px;
  color: #666;
  margin-bottom: 10px;
}

.item-price {
  color: #e74c3c;
  font-size: 18px;
  margin-bottom: 20px;
}

.seckill-price {
  font-size: 28px;
}

.original-price {
  margin-left: 10px;
  color: #999;
}

.van-divider {
  margin: 20px 0;
}
</style>